import emojimap from './emojimap.js'
var emoji = emojimap.emojiList.emoji
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}
// 时间戳转化为 10
export function formatSeconds (value, num) {
  let date = new Date().getTime()
  let newValue = date - value
  var secondTime = parseInt(newValue / 1000)
  var minuteTime = 0
  var hourTime = 0
  if (secondTime > 60) {
    minuteTime = parseInt(secondTime / 60)
    secondTime = parseInt(secondTime % 60)
    if (minuteTime > 60) {
      hourTime = parseInt(minuteTime / 60)
      minuteTime = parseInt(minuteTime % 60)
    }
  }
  if (minuteTime < 1 && hourTime < 1 && secondTime >= 0) {
    return '' + parseInt(secondTime) + '秒以前'
  } else if (minuteTime > 1 && hourTime < 1) {
    return '' + parseInt(minuteTime) + '分' + parseInt(secondTime) + '秒以前'
  } else if (hourTime >= 1) {
    return '' + parseInt(hourTime) + '小时以前'
  } else {
    return '刚刚'
  }
}
export function filterTime (value, count) {
  let date = new Date(value * 1000)
  let y = date.getFullYear()
  let MM = date.getMonth() + 1
  MM = MM < 10 ? ('0' + MM) : MM
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d
  let h = date.getHours()
  h = h < 10 ? ('0' + h) : h
  let m = date.getMinutes()
  m = m < 10 ? ('0' + m) : m
  let s = date.getSeconds()
  s = s < 10 ? ('0' + s) : s
  if (count === 1) {
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
  } else if (count === 2) {
    return y + '-' + MM + '-' + d
  } else if (count === 3) {
    return y + '年' + MM + '月' + d + '日'
  } else if (count === 4) {
    return y + '年' + MM + '月' + d + '日' + ' ' + h + ':' + m + ':' + s
  } else if (count === 5) {
    return MM + '-' + d + ' ' + h + ':' + m
  } else if (count === 6) {
    return h + ':' + m
  } else if (count === 7) {
    return y + '年' + MM + '月' + d + '日' + '　' + h + ':' + m
  } else if (count === 8) {
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m
  } else if (count === 9) {
    return y + MM + d
  }
}
export function countDown (t) {
  let day = Math.floor(t / 86400000);
  let hour = Math.floor((t / 3600000) % 24);
  let min = Math.floor((t / 60000) % 60);
  let sec = Math.floor((t / 1000) % 60);
  hour = hour < 10 ? "0" + hour : hour;
  min = min < 10 ? "0" + min : min;
  sec = sec < 10 ? "0" + sec : sec;
  let format = '';
  if (day > 0) {
    format = `${day}天${hour}时${min}分${sec}秒`;
  }
  if (day <= 0 && hour > 0) {
    format = `${hour}时${min}分${sec}秒`;
  }
  if (day <= 0 && hour <= 0) {
    format = `${min}分${sec}秒`;
  }
  return format
}
function calcTimeHeader(time) {
  // 格式化传入时间
  let date = new Date(parseInt(time)),
    year = date.getUTCFullYear(),
    month = date.getUTCMonth(),
    day = date.getDate(),
    hour = date.getHours(),
    minute = date.getUTCMinutes()
  // 获取当前时间
  let currentDate = new Date(),
    currentYear = date.getUTCFullYear(),
    currentMonth = date.getUTCMonth(),
    currentDay = currentDate.getDate()
  // 计算是否是同一天
  if (currentYear == year && currentMonth == month && currentDay == day) {//同一天直接返回
    if (hour > 12) {
      return `下午 ${hour}:${minute < 10 ? '0' + minute : minute}`
    } else {
      return `上午 ${hour}:${minute < 10 ? '0' + minute : minute}`
    }
  }
  // 计算是否是昨天
  let yesterday = new Date(currentDate - 24 * 3600 * 1000)
  if (year == yesterday.getUTCFullYear() && month == yesterday.getUTCMonth && day == yesterday.getDate()) {//昨天
    return `昨天 ${hour}:${minute < 10 ? '0' + minute : minute}`
  } else {
    return `${year}-${month + 1}-${day} ${hour}:${minute < 10 ? '0' + minute : minute}`
  }
}
// 生成富文本节点
function generateRichTextNode(text) {
  let tempStr = text
  let richTextNode = []
  let leftBracketIndex = tempStr.indexOf('[')
  let rightBracketIndex = tempStr.indexOf(']')
  let countOfWord = 0
  Array.from(tempStr).map(item => {
    if (item != '[' && item != ']') {
      countOfWord++
    }
  })
  if (leftBracketIndex == -1 || rightBracketIndex == -1 || countOfWord == 0) {//没有emoji
    richTextNode.push({
      type: 'text',
      text: tempStr
    })
    return richTextNode
  }
  while (tempStr.length != 0) {
    leftBracketIndex = tempStr.indexOf('[')
    rightBracketIndex = tempStr.indexOf(']')
    if (leftBracketIndex == 0) { // 开头是[
      rightBracketIndex = tempStr.indexOf(']')
      if (rightBracketIndex == -1) {
        richTextNode.push({
          type: 'text',
          text: tempStr
        })
        tempStr = ''
      } else {
        let emojiName = tempStr.slice(0, rightBracketIndex + 1)
        if (emoji[emojiName]) { // 有效emoji
          richTextNode.push({
            name: 'img',
            attrs: {
              width: '30rpx',
              height: '30rpx',
              src: emoji[emojiName].img
            }
          })
        } else {//无效emoji
          richTextNode.push({
            type: 'text',
            text: emojiName
          })
        }
        tempStr = tempStr.substring(rightBracketIndex + 1, tempStr.length)
      }
    } else { // 开头不是[
      if (leftBracketIndex == -1) {// 最后全是文字
        richTextNode.push({
          type: 'text',
          text: tempStr.slice(0, tempStr.length)
        })
        tempStr = ''
      } else {
        richTextNode.push({
          type: 'text',
          text: tempStr.slice(0, leftBracketIndex)
        })
        tempStr = tempStr.substring(leftBracketIndex, tempStr.length + 1)
      }
    }
  }
  return richTextNode
}
// 处理图片富文本节点
function generateImageNode(file) {
  // console.log(file)
  let width = 0, height = 0
  if (file.w > 250) {
    width = 200
    height = file.h / (file.w / 200)
  } else {
    width = file.w
    height = file.h
  }
  let richTextNode = []
  richTextNode.push({
    name: 'img',
    attrs: {
      width: `${width}rpx`,
      height: `${height}rpx`,
      src: file.url
    }
  })
  return richTextNode
}
/**
   * 输出贴图表情对象，用于生成富文本图片节点
   * content:"{"type":3,"data":{"catalog":"ajmd","chartlet":"ajmd010"}}"
   */
function generateBigEmojiImageFile(content) {
  let prefix = 'http://yx-web.nosdn.127.net/webdoc/h5/emoji/'
  let file = { w: 100, h: 100, url: '' }
  file.url = `${prefix}${content.data.catalog}/${content.data.chartlet}.png`
  return file
}
/**
 * 输出猜拳图片对象，用于生成富文本图片节点
 */
function generateFingerGuessImageFile(value) {
  let file = { w: 50, h: 50, url: '' }
  switch (value) {
    case 1:
      file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-1.png'
      break
    case 2:
      file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-2.png'
      break
    case 3:
      file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-3.png'
      break
    default:
      break
  }
  return file
}
/**
 * 封装toast
 */
function showToast (type, text, obj) {
  let param = { duration: (obj && obj.duration) || 1500, mask: (obj && obj.isMask) || false }
  switch(type) {
    case 'text': {
      param['title'] = text || ''
      param['icon'] = 'none'
      break
    }
    case 'loading': {
      param['title'] = text || ''
      param['icon'] = 'loading'
      break
    }
    case 'success': {
      param['title'] = text || ''
      param['icon'] = 'success'
      break
    }
    case 'error': {
      param['title'] = text || ''
      param['image'] = '/images/emoji.png'
      break
    }
    default: {
      break
    }
  }
  mpvue.showToast(param)
}
function finisApt (item) {
  let app = getApp()
  let newObject = {
    // 多个就诊人区分
    regular_id: item.regular_id + '',
    category: item.category + '',
    aptId: item.apt_id,
    finishApt: true
  }
  app.globalData.nim.sendTipMsg({
    scene: 'p2p',
    to: item.netease_id,
    tip: '结束问诊!',
    isUnreadable: false,
    custom: JSON.stringify(newObject),
    done: (err, msg) => {}
  })
}
export default {
  formatNumber,
  formatTime,
  formatSeconds,
  calcTimeHeader,
  generateRichTextNode,
  generateImageNode,
  generateBigEmojiImageFile,
  generateFingerGuessImageFile,
  showToast,
  filterTime,
  finisApt,
  countDown
}
